import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:huxiaodui/background_run/bg_channel.dart';
import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/api/model/alarm_model.dart';
import 'package:huxiaodui/utils/global_controller.dart';
import 'package:huxiaodui/main.dart';
import 'package:huxiaodui/view/index/map_page/map_controller.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
class AlarmDialog {
  static bool isShowAlarm = false;
  static Future<void> show(Map<String,dynamic> data) async {
    if (isShowAlarm) return;
    isShowAlarm = true;

    AlarmModel alarm = AlarmModel.fromJson(data);
    MapController().alarms.insert(0, alarm);
    MapController().refresh();
    MapController().updateMarkers();

    await showCupertinoDialog(
      barrierDismissible: false,
      context: navigatorKey.currentState!.context,
      builder: (BuildContext context) {
        return Container(
          color: Colors.black.withAlpha(90),
          child: CupertinoAlertDialog(
            title: const Text("警报"),
            content: Text(alarm.unit.name),
            actions: [CupertinoDialogAction(
              textStyle: TextStyle(
                  color: Theme.of(context).textTheme.bodyMedium?.color, fontWeight: FontWeight.w700),
              child: const Text('取消'),
              onPressed: () async {
                Navigator.pop(context);
              },
            ),CupertinoDialogAction(
              textStyle: TextStyle(
                  color: Theme.of(context).textTheme.bodyMedium?.color, fontWeight: FontWeight.w700),
              child: const Text('确定'),
              onPressed: () async {

                Navigator.pop(context);
                if(alarm.latLng!=null || alarm.unit.latLng!=null) {
                  GlobalController.toFirst(showDrawer: false);
                  MapController().moveCenter(alarm.latLng ?? alarm.unit.latLng!);
                  MapController().showMarker(alarm);

                }else{
                  EasyLoading.showError("没有定位消息！");
                }
              },

            ),],
          ),
        );
      },
    );
    Api.mobileApp.alarmClear();
    FlutterLocalNotificationsPlugin().cancel(1001);
    FlutterBackgroundService().invoke(BgChannelType.stopAlarm);
    Future.delayed(const Duration(seconds: 1)).then((value){
      isShowAlarm = false;
    });
  }
}
